package com.jeequan.jeepay.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

public class CommonUtil {
    private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    public static boolean stringEmpty(CharSequence charSequence) {
        return (charSequence == null || charSequence.length() == 0 || charSequence == "null" || charSequence == "");
    }

    public static boolean mapEmpty(Map<?, ?> paramMap) {
        return (null == paramMap || paramMap.isEmpty());
    }

    public static boolean iterableEmpty(Iterable<?> iterable) {
        return (null == iterable || isEmpty(iterable.iterator()));
    }

    public static boolean iteratorEmpty(Iterator<?> iterator) {
        return (null == iterator || !iterator.hasNext());
    }

    public static boolean isArray(Object obj) {
        if (null == obj)
            return false;
        return obj.getClass().isArray();
    }

    public static boolean arrayEmpty(Object obj) {
        if (null == obj)
            return true;
        if (isArray(obj))
            return (0 == Array.getLength(obj));
        throw new BizException("Object to provide is not a Array !");
    }

    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

    public static boolean isEmpty(Object obj) {
        if (null == obj)
            return true;
        if (obj instanceof CharSequence)
            return stringEmpty((CharSequence)obj);
        if (obj instanceof Map)
            return mapEmpty((Map<?, ?>)obj);
        if (obj instanceof Iterable)
            return iterableEmpty((Iterable)obj);
        if (obj instanceof Iterator)
            return iteratorEmpty((Iterator)obj);
        if (isArray(obj))
            return arrayEmpty(obj);
        return false;
    }

    public static boolean notEmpty(Object obj) {
        return !isEmpty(obj);
    }

//    public static String a(String paramString1, String paramString2, String paramString3) {
//        return b(paramString1, paramString2, paramString3);
//    }

    public static boolean isNumber(String param) {
        return param.matches("-?[0-9]+.?[0-9]*");
    }

//    private static String b(String paramString1, String paramString2, String paramString3) {
//        String str = null;
//        if (paramString1 == null || "".equals(paramString1.trim()))
//            return paramString1;
//        try {
//            byte[] arrayOfByte = paramString1.getBytes(paramString2);
//            for (byte b = 0; b < arrayOfByte.length; b++)
//                System.out.print(arrayOfByte[b] + "  ");
//            str = new String(arrayOfByte, paramString3);
//        } catch (Exception exception) {
//            exception.printStackTrace();
//            return null;
//        }
//        return str;
//    }

    public static int formatIntByStr(String str, int defaultValue) {
        if (StringUtils.isBlank(str))
            return defaultValue;
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException numberFormatException) {
            logger.error(numberFormatException.getMessage(), numberFormatException);
            return defaultValue;
        }
    }

    public static int formatIntByStr(String str) {
        return formatIntByStr(str, 0);
    }

//    public static int a(String paramString, Integer paramInteger) {
//        if (paramString == null || paramString == "")
//            return paramInteger.intValue();
//        try {
//            return Integer.parseInt(paramString);
//        } catch (NumberFormatException numberFormatException) {
//            logger.error(numberFormatException.getMessage(), numberFormatException);
//            return 0;
//        }
//    }

    public static int formatInt(Object param, int defaultValue) {
        if (isEmpty(param))
            return defaultValue;
        try {
            if (param instanceof Float)
                return ((Float) param).intValue();
            return Integer.parseInt(param.toString());
        } catch (NumberFormatException numberFormatException) {
            logger.error(numberFormatException.getMessage(), numberFormatException);
            return defaultValue;
        }
    }

    public static Integer formatInt(Object paramObject) {
        if (isEmpty(paramObject))
            return null;
        try {
            if (paramObject instanceof Float)
                return ((Float) paramObject).intValue();
            return Integer.parseInt(paramObject.toString());
        } catch (NumberFormatException numberFormatException) {
            logger.error(numberFormatException.getMessage(), numberFormatException);
            return null;
        }
    }

    public static int formatInt(BigDecimal bigDecimal, int defaultValue) {
        if (bigDecimal == null)
            return defaultValue;
        return bigDecimal.intValue();
    }

    public static String getString(String paramString) {
        return getString(paramString, "");
    }

    public static String getStringByObj(Object obj) {
        return getStringByObj(obj, "");
    }

    public static String formatStr(int paramInt) {
        return String.valueOf(paramInt);
    }

    public static String formatStr(float paramFloat) {
        return String.valueOf(paramFloat);
    }

    public static String getString(String str, String defaultValue) {
        if (isEmpty(str))
            return defaultValue;
        return str.trim();
    }

    public static String getStringByObj(Object str, String defaultValue) {
        if (isEmpty(str))
            return defaultValue;
        return str.toString().trim();
    }

    public static String formatStr(Object paramObject) {
        if (isEmpty(paramObject))
            return "";
        return paramObject.toString();
    }

    public static String getIp() {
        String str = null;
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            str = inetAddress.getHostAddress();
        } catch (UnknownHostException unknownHostException) {
            unknownHostException.printStackTrace();
        }
        return str;
    }

    public static String d(String paramString) {
        byte b1 = 3;
        if (paramString.length() < b1)
            return paramString.toLowerCase();
        StringBuilder stringBuilder = new StringBuilder(paramString);
        byte b2 = 0;
        for (byte b3 = 2; b3 < paramString.length(); b3++) {
            if (Character.isUpperCase(paramString.charAt(b3))) {
                stringBuilder.insert(b3 + b2, "_");
                b2++;
            }
        }
        return stringBuilder.toString().toLowerCase();
    }

    public static Field[] getFields(Object paramObject) {
        Class<?> clazz = paramObject.getClass();
        List<?> arrayList = new ArrayList<>();
        while (clazz != null) {
            arrayList.addAll(new ArrayList(Arrays.asList((Object[])clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] arrayOfField = new Field[arrayList.size()];
        arrayList.toArray((Object[])arrayOfField);
        return arrayOfField;
    }

    public static String a(Object[] paramArrayOfObject, String paramString, int paramInt1, int paramInt2) {
        if (paramArrayOfObject == null)
            return null;
        if (paramString == null)
            paramString = "";
        int i = paramInt2 - paramInt1;
        if (i <= 0)
            return "";
        StringBuilder stringBuilder = getStringBuilder(i);
        if (paramArrayOfObject[paramInt1] != null)
            stringBuilder.append(paramArrayOfObject[paramInt1]);
        for (int j = paramInt1 + 1; j < paramInt2; j++) {
            stringBuilder.append(paramString);
            if (paramArrayOfObject[j] != null)
                stringBuilder.append(paramArrayOfObject[j]);
        }
        return stringBuilder.toString();
    }

    private static StringBuilder getStringBuilder(int paramInt) {
        return new StringBuilder(paramInt * 16);
    }

    // 查找子字符串
    public static int findSubstring(CharSequence sequence1, CharSequence sequence2, int startIndex) {
        if (sequence1  == null || sequence2 == null)
            return -1;
        if (startIndex < 0)
            startIndex = 0;
        int i = sequence1.length() - sequence2.length() + 1;
        if (startIndex > i)
            return -1;
        if (sequence2.length() == 0)
            return startIndex;
        for (int j = startIndex; j < i; j++) {
            if (regionMatches(sequence1 , true, j, sequence2, 0, sequence2.length()))
                return j;
        }
        return -1;
    }

    public static boolean regionMatches(CharSequence sequence1, boolean ignoreCase, int startIndex1, CharSequence sequence2, int startIndex2, int length) {
        if (sequence1 instanceof String && sequence2 instanceof String)
            return ((String)sequence1).regionMatches(ignoreCase, startIndex1, (String)sequence2, startIndex2, length);
        int i = startIndex1;
        int j = startIndex2;
        int k = length;
        int m = sequence1.length() - startIndex1;
        int n = sequence2.length() - startIndex2;
        if (startIndex1 < 0 || startIndex2 < 0 || length < 0)
            return false;
        if (m < length || n < length)
            return false;
        while (k-- > 0) {
            char c1 = sequence1.charAt(i++);
            char c2 = sequence2.charAt(j++);
            if (c1 == c2)
                continue;
            if (!ignoreCase)
                return false;
            if (Character.toUpperCase(c1) != Character.toUpperCase(c2) &&
                    Character.toLowerCase(c1) != Character.toLowerCase(c2))
                return false;
        }
        return true;
    }

    public static byte[] decodeByBase64(String paramString) {
        return Base64.decodeBase64(paramString);
    }

    public static <T> List<T> a(List<T> paramList) {
        try{
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(paramList);
        } catch (Exception exception) {
            logger.warn(exception.getMessage());
            return Collections.emptyList();
        }
        return paramList;
    }

    public static JSONObject convertJson(JSONObject json) {
        if (null != json && json.size() > 0)
            return JSONObject.parseObject(json.toJSONString());
        return new JSONObject();
    }
}
